<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Utils\EncryptUtil;
use Hyperf\Context\Context;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;

class DecryptMiddleware implements MiddlewareInterface
{
    /**
     * 处理请求
     *
     * @param ServerRequestInterface $request 请求对象
     * @param RequestHandlerInterface $handler 请求处理器
     * @return ResponseInterface 响应对象
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 非正式环境不解密
        if (!is_prod()) {
            return $handler->handle($request);
        }

        // 获取请求加密数据
        $encryptData = $request->getBody()->getContents();

        // 使用工具类解密数据，传入设备指纹作为自定义盐值
        $decryptedData = EncryptUtil::decrypt($encryptData, get_device_identifier());
        throw_error_if(empty($decryptedData), "请求参数解密失败");

        // 将解密后的数据重新设置到请求中
        $request = $request->withParsedBody($decryptedData);

        // 将修改后的请求对象存储到上下文中
        Context::set(ServerRequestInterface::class, $request);

        return $handler->handle($request);
    }
} 